<template>
  <div id="ClassificationIndex">
    <main-header :title="'分类管理'" :crumbsArr="crumbsArr" />
    <div class="main">
      <div style="padding: 20px; background: #fff;" v-loading="treeLoading">
        <el-tree
          ref="tree"
          :data="classificationTree"
          :load="loadNode"
          lazy
        >
          <span
            class="custom-tree-node"
            slot-scope="{ node, data }"
            @mouseover="eOverNode($event, `${node.level}_${node.id}`)"
            @mouseout="eOutNode($event, `${node.level}_${node.id}`)"
          >
            <span>{{ node.label }}</span>
            <span class="btn_block" :ref="`${node.level}_${node.id}`">
              <el-button
                class="add"
                type="text"
                size="mini"
                @click="() => addBtnClick(node, data)">
                添加
              </el-button>
              <!--<el-button-->
                <!--class="rename"-->
                <!--type="text"-->
                <!--size="mini"-->
                <!--@click="() => renameBtnClick(node, data)">-->
                <!--重命名-->
              <!--</el-button>-->
              <el-button
                class="delete"
                type="text"
                size="mini"
                @click="() => removeBtnClick(node, data)">
                删除
              </el-button>
            </span>
          </span>
        </el-tree>
      </div>
    </div>

    <!-- 添加/编辑 dialog -->
    <el-dialog
      :title="addOrEditTitle"
      :visible.sync="addNodeVis"
      @close="addDialogClose('addForm')"
    >
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="addForm.name" :disabled="beAdding"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogClose('addForm')">取 消</el-button>
        <el-button type="primary" @click="addNodeOk('addForm')" :loading="beAdding">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 删除确认 dialog -->
    <el-dialog
      title="提示"
      :visible.sync="delNodeVis"
      width="30%"
    >
      <span>确认删除？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delNodeVis = false">取 消</el-button>
        <el-button type="primary" @click="delNodeOk" :loading="beAdding">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import MainHeader from '@/components/layouts/MainHeader'
import API from '@/config/api.js'
import ErrorConfig from '@/config/error.config.js'

export default {
  name: 'ClassificationIndex',
  data () {
    return {
      crumbsArr: [ // 面包屑
        { name: 'welcome', txt: '首页' }, { txt: '分类管理' }
      ],
      pageInfo: {
        pageCount: 1,
        pageSize: 0,
        currentPage: 1
      },
      classificationTree: [],
      treeLoading: false,
      addNodeVis: false,
      delNodeVis: false,
      beAdding: false,
      addFormRules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      addForm: {
        name: ''
      },
      beHandlingNode: {
        node: null,
        data: null
      },
      addOrEditTitle: '添加'
    }
  },
  components: {
    MainHeader
  },
  beforeRouteEnter (to, from, next) {
    next(vm => vm.initPage())
  },
  watch: {
    // '$route' (to, from) {
    //   if (to.name === 'classification') {
    //     this.initPage()
    //   }
    // }
  },
  methods: {
    initPage () { // 初始化页面数据
      this.loadNode()
    },
    async loadNode (node, resolve) { // 加载节点数据
      const params = {}
      if (node) { // 非首次加载
        params.id = node.data.id
      } else {
        this.treeLoading = true
      }
      const response = await API.getTypeList(params)
      const { code, data } = response
      if (code === 1) {
        let arr = []
        for (let item of data) {
          arr.push({
            id: item.id,
            label: item.name
          })
        }
        if (!node) { // 首次加载
          this.classificationTree = Object.assign([], arr)
          this.treeLoading = false
        } else { // 非首次加载
          return resolve(arr)
        }
      } else {
        if (code === -1) {
          const { msg } = response
          this.$message.error(msg)
        } else {
          this.$message.error(ErrorConfig[code])
        }
        if (!node) { // 首次加载
          this.treeLoading = false
        } else { // 非首次加载
          return resolve([])
        }
      }
    },
    eOverNode (e, btnEl) { // 鼠标移动到节点上面
      this.$refs[btnEl].style.display = 'block'
    },
    eOutNode (e, btnEl) { // 鼠标移出节点
      this.$refs[btnEl].style.display = 'none'
    },
    addBtnClick (node, data) { // 添加孩子节点
      this.addOrEditTitle = '添加'
      this.beHandlingNode.data = data
      this.beHandlingNode.node = node
      this.addNodeVis = true
    },
    addDialogClose (formName) {
      this.addNodeVis = false
      this.$refs[formName].resetFields()
    },
    addNodeOk (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.beAdding = true // 加载中
          let { data, node } = this.beHandlingNode
          let { name } = this.addForm
          const response = await API.addSeriess({ name, parentId: data.id })
          const { code } = response
          this.beAdding = false
          if (code === 1) {
            const nodeInfo = response.data
            this.addDialogClose(formName) // 关闭并重置新增dialog
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            const newChild = { id: nodeInfo.id, label: nodeInfo.name, children: [] }
            this.$refs.tree.append(newChild, node)
          } else {
            if (code === -1) {
              const { msg } = response
              this.$message.error(msg)
            } else {
              this.$message.error(ErrorConfig[code])
            }
          }
        } else {
          return false
        }
      })
    },
    renameBtnClick (node, data) {
      this.addOrEditTitle = '重命名'
      this.beHandlingNode.data = data
      this.addNodeVis = true
    },
    removeBtnClick (node, data) {
      this.beHandlingNode.data = data
      this.beHandlingNode.node = node
      this.delNodeVis = true
    },
    async delNodeOk () {
      this.beAdding = true
      let { data, node } = this.beHandlingNode
      const parent = node.parent
      const children = parent.childNodes
      const index = children.findIndex(n => n.data.id === data.id)
      const response = await API.deleteSeriess({ id: data.id })
      const { code } = response
      if (code === 1) {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.beAdding = false
        this.delNodeVis = false
        children.splice(index, 1) // 视图上删除对应的节点
      } else {
        if (code === -1) {
          const { msg } = response
          this.$message.error(msg)
        } else {
          this.$message.error(ErrorConfig[code])
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
  #ClassificationIndex {
    .main {
      padding: 20px 20px 0;
      .el-tree {
        .custom-tree-node {
          flex: 1;
          display: flex;
          align-items: center;
          /*justify-content: space-between;*/
          font-size: 14px;
          line-height: 24px;
          color: #000;
          .btn_block {
            display: none;
            margin-left: 40px;
            .el-button {
              color: #555;
              &.delete {
                color: #dd6161;
              }
            }
          }
        }
      }
    }
  }
</style>
